package com.gdpa.controller;

import com.gdpa.entity.SysUser;
import com.gdpa.entity.vo.ResponseData;
import com.gdpa.service.ICheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/check")
public class CheckController {

    HttpSession session;
    HttpServletRequest request;
    @Autowired
    ICheckService checkService;

    @RequestMapping("/check-login")
    @ResponseBody
    public ResponseData Login(SysUser sysUser) throws Exception {

        String msg="fail";
        SysUser user=checkService.checkLogin(sysUser);
        System.out.println(user);
        //判断用户名及密码是否正确，正确则登录，错误则提示重新输入
        if(user!=null){
            //设置字符集
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session=request.getSession();
            session.setAttribute("userId",user.getUserId());
            session.setAttribute("userName",user.getUserName());
            session.setAttribute("pwd",user.getPwd());
            session.setAttribute("part",user.getPart());
            msg = "success";
            return ResponseData.okMsg(msg);

        }else{
            return ResponseData.failMsg(msg);
        }
    }

    @PostMapping("/logout")
    public ResponseData Logout(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        session.invalidate();
        return ResponseData.okMsg("退出成功！");
    }

    @PostMapping("/check-role")
    public SysUser checkMenu(){
        request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        session=request.getSession();
        String userName = (String) session.getAttribute("userName");
        Integer part = (Integer) session.getAttribute("part");
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setPart(part);
        System.out.println(sysUser);
        return sysUser;
    }

}
